﻿using Ewell.BizComponent.UI.Core.VievModel;
using Ewell.Interface.Common.Model.Common;
using Ewell.Interface.Common.Model.GateWay.Dto.Out;
using Ewell.Interface.Common.Model.GateWay.GateWayUriInfo;
using MahApps.Metro.Controls;
using MahApps.Metro.Controls.Dialogs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using Ewell.Interface.Common.Utils;
using Ewell.BizComponent.UI.Core.ViewModel;
using Ewell.Interface.Common.Model.GateWay.Dto.Dict;
using System.Windows;
using Ewell.BizComponent.UI.Reserve.Model.Response;
using Ewell.BizComponent.UI.Core.Model;

namespace Ewell.BizComponent.UI.Reserve.ViewModel
{
    /// <summary>
    /// 门诊预约主类
    /// </summary>
    public class OutpReserveVm : ViewModelBase
    {
        /// <summary>
        /// 外部调用请求
        /// </summary>
        public OutpReserveRequestVm outpReserveRequestVm { get; set; }
        /// <summary>
        /// 患者
        /// </summary>
        private PatientVm _patientVm;
        public PatientVm patientVm
        {
            get => _patientVm;
            set
            {
                if (value != _patientVm)
                {
                    _patientVm = value;
                    OnPropertyChanged(nameof(patientVm));
                }
            }
        }
        /// <summary>
        /// 就诊日期
        /// </summary>
        private DateTime? _visitDate;
        public DateTime? visitDate
        {
            get => _visitDate;
            set
            {
                if (_visitDate != value)
                {
                    _visitDate = value;
                    OnPropertyChanged(nameof(visitDate));
                }
            }
        }
        /// <summary>
        /// 所有就诊服务提供者
        /// </summary>
        private List<EsProviderInfoVm> _allEsProviderInfoVmList;
        public List<EsProviderInfoVm> allEsProviderInfoVmList
        {
            get => _allEsProviderInfoVmList;
            set
            {
                if (value != _allEsProviderInfoVmList)
                {
                    _allEsProviderInfoVmList = value;
                    OnPropertyChanged(nameof(allEsProviderInfoVmList));
                }
            }
        }
        /// <summary>
        /// 就诊服务提供者
        /// </summary>
        private List<EsProviderInfoVm> _esProviderInfoVmList;
        public List<EsProviderInfoVm> esProviderInfoVmList
        {
            get => _esProviderInfoVmList;
            set
            {
                if(value != _esProviderInfoVmList)
                {
                    _esProviderInfoVmList = value;
                    OnPropertyChanged(nameof(esProviderInfoVmList));
                }
            }
        }
        /// <summary>
        /// 选中的服务提供者
        /// </summary>
        private EsProviderInfoVm _selectedEsProviderInfo;
        public EsProviderInfoVm selectedEsProviderInfo
        {
            get => _selectedEsProviderInfo;
            set
            {
                if (value != _selectedEsProviderInfo)
                {
                    _selectedEsProviderInfo = value;
                    OnPropertyChanged(nameof(selectedEsProviderInfo));
                }
            }
        }
        /// <summary>
        /// 排班信息
        /// </summary>
        private List<ScheduleVm> _scheduleVmList;
        public List<ScheduleVm> scheduleVmList
        {
            get
            {
                return _scheduleVmList;
            }
            set
            {
                if (_scheduleVmList != value)
                {
                    _scheduleVmList = value;
                    OnPropertyChanged(nameof(scheduleVmList));
                }
            }
        }
        /// <summary>
        /// 选中的排班
        /// </summary>
        private ScheduleVm _selectedScheduleVm;
        public ScheduleVm selectedScheduleVm
        {
            get => _selectedScheduleVm;
            set
            {
                if( value != _selectedScheduleVm)
                {
                    _selectedScheduleVm = value;
                    OnPropertyChanged(nameof(selectedScheduleVm));
                }
            }
        }
        /// <summary>
        /// 预约结果
        /// </summary>
        public OutpReserveResponse outpReserveResponse { get; set; }
        public Window localWindow { get; set; }

        /// <summary>
        /// 预约显示
        /// </summary>
        private Visibility _reserveVisib=Visibility.Collapsed;
        public Visibility reserveVisib
        {
            get => _reserveVisib;
            set
            {
                if( _reserveVisib != value)
                {
                    _reserveVisib = value;
                    OnPropertyChanged(nameof(reserveVisib));
                }
            }
        }
        public IDialogCoordinator dialogCoordinator { get; set; } = DialogCoordinator.Instance;

        /// <summary>
        /// 查询排班
        /// </summary>
        public ICommand QuerySchedule => new RelayCommand(async (object param) =>
        {
            if(!visitDate.HasValue)
            {
                await dialogCoordinator.ShowMessageAsync(this, "提醒!", "请选择就诊日期!");
                return;
            }
            List<ScheduleVm> scheduleList = new List<ScheduleVm>();
            QueryScheduleByExampleV1Request request = new QueryScheduleByExampleV1Request()
            {
                scheduleDateBegin = visitDate,
                scheduleDateEnd = visitDate.Value.AddDays(1).AddSeconds(-1),
                encResTypeCodings = new List<string>() { "2" },
                bizSourceCoding = LoginInfo.loginUser.bizSourceCode == "14" ? "4" : LoginInfo.loginUser.bizSourceCode,
                searchAllDayFlag = "1",
                providerId = selectedEsProviderInfo?.esProviderId,
                providerTypeCoding = selectedEsProviderInfo?.esProviderTypeCoding//就诊服务提供者类型代码 1科室2医生
            };
            ScheduleManageDubboService scheduleManageDubboService = new ScheduleManageDubboService();
            var gateWayResult = scheduleManageDubboService.queryScheduleByExampleV1.Post<List<OutScheduleDTO>>(request);
            if (!gateWayResult.success) throw new SpeedException("HISBIZ", gateWayResult.message);
            if (gateWayResult.@object == null) return;
            foreach (var item in gateWayResult.@object)
            {
                ScheduleVm schedule = new ScheduleVm();
                schedule.encScheduleId = item.encScheduleId;
                schedule.scheduleDate=item.scheduleDate;
                schedule.msId = item.msId;
                schedule.msName = item.msName;
                schedule.registrationTypeId = item.registrationTypeId;
                schedule.registrationTypeName = item.registrationTypeName;
                schedule.regCategoryId = item.regCategoryId;
                schedule.quantity = item.quantity;
                schedule.quantityUsed = item.quantityUsed;
                schedule.quantityRemain = item.quantityRemain;
                schedule.regAmount = item.regAmount;
                schedule.noonTypeId = item.noonTypeId;
                schedule.noonTypeCoding = item.noonTypeCoding;
                schedule.noonTypeName = item.noonTypeName;
                schedule.beginTime = item.beginTime;
                schedule.endTime = item.endTime;
                schedule.providerId = item.providerId;
                schedule.providerTypeCoding = item.providerTypeCoding;
                schedule.docId = item.providerTypeCoding == "2" ? item.providerId : "";
                schedule.docCode = item.providerTypeCoding == "2" ? LoginInfo.loginUser.userId : "";
                schedule.docName = item.providerTypeCoding == "2" ? item.providerName : "";
                schedule.deptId = item.providerTypeCoding == "1" ? item.providerId : LoginInfo.loginUser.deptCode;
                schedule.deptCode = item.providerTypeCoding == "1" ? LoginInfo.loginUser.deptCode : "";
                schedule.deptName = item.providerTypeCoding == "1" ? item.providerName : LoginInfo.loginUser.deptName;
                List<EsSlotSettingVm> esSlotList = new List<EsSlotSettingVm>();
                if (item.esSlotSettingList != null)
                {
                    foreach (var esSlot in item.esSlotSettingList)
                    {
                        EsSlotSettingVm esSlotSetting = new EsSlotSettingVm()
                        {
                            esSlotSettingId = esSlot.esSlotSettingId,
                            quantity = esSlot.quantity,
                            quantityPlaned = esSlot.quantityPlaned,
                            quantityRemain = esSlot.quantityRemain,
                            quantityUsed = esSlot.quantityUsed,
                            beginAtTime = esSlot.beginAtTime,
                            endAtTime = esSlot.endAtTime,
                        };
                        esSlotList.Add(esSlotSetting);
                    }
                }
                schedule.esSlotSettingList = esSlotList;
                scheduleList.Add(schedule);
            }
            scheduleVmList=scheduleList;
        });
        /// <summary>
        /// 查询服务提供者
        /// </summary>
        public ICommand QueryESProvider => new RelayCommand(async (object param) =>
        {
            List<EsProviderInfoVm> providerInfoVmList = new List<EsProviderInfoVm>();
            QueryESDeptRequest request = new QueryESDeptRequest()
            {
                esProviderTypeCoding = "1",
            };
            DictEncounterDubboService dictEncounterDubboService = new DictEncounterDubboService();
            var gateWayResult=dictEncounterDubboService.queryESProviderByExample.Post<List<EsProviderInfoVm>>(request);
            if(!gateWayResult.success)
            {
                await dialogCoordinator.ShowMessageAsync(this,"警告!", $"查询出诊者失败!{gateWayResult.message}");
                return;
            }
            providerInfoVmList = gateWayResult.@object;
            request.esProviderTypeCoding = "2";
            gateWayResult = dictEncounterDubboService.queryESProviderByExample.Post<List<EsProviderInfoVm>>(request);
            if (!gateWayResult.success)
            {
                await dialogCoordinator.ShowMessageAsync(this, "警告!", $"查询出诊者失败!{gateWayResult.message}");
                return;
            }
            providerInfoVmList.AddRange(gateWayResult.@object);
            this.allEsProviderInfoVmList = providerInfoVmList;
            this.esProviderInfoVmList = allEsProviderInfoVmList;
            if(outpReserveRequestVm!=null&& !string.IsNullOrWhiteSpace(outpReserveRequestVm.docId))
            {
                this.selectedEsProviderInfo = this.allEsProviderInfoVmList.FirstOrDefault(f => f.esProviderId == outpReserveRequestVm.docId);
            }
        });

        /// <summary>
        /// 预约显示
        /// </summary>
        public ICommand ReserveVisib => new RelayCommand((object param) =>
        {
            reserveVisib = Visibility.Visible;
        });
        /// <summary>
        /// 预约显示
        /// </summary>
        public ICommand CancelReserveVisib => new RelayCommand((object param) =>
        {
            reserveVisib = Visibility.Collapsed;
        });
        
        /// <summary>
        /// 预约
        /// </summary>
        public ICommand Reserve => new RelayCommand(async (object param) =>
        {
            var esSlotSetting=param as EsSlotSettingVm;
            if (esSlotSetting == null)
            {
                await dialogCoordinator.ShowMessageAsync(this, "警告!", "未选择预约时段!");
                return;
            }
            if(patientVm==null|| string.IsNullOrWhiteSpace(patientVm.patientId))
            {
                await dialogCoordinator.ShowMessageAsync(this, "警告!", "未选择患者!");
                return;
            }
            EncounterReservedRequest reservedRequest = new EncounterReservedRequest()
            {
                patientId = patientVm.patientId,
                bizSourceCoding=LoginInfo.loginUser.bizSourceCode,
                encScheduleId=selectedScheduleVm.encScheduleId,
                esSlotSettingId=esSlotSetting.esSlotSettingId,
                msId=selectedScheduleVm.msId,
                needPayFlag="0",
            };
            ScheduleManageDubboService scheduleManageDubboService = new ScheduleManageDubboService();
            var gateWayResult=scheduleManageDubboService.encounterReserved.Post<OutpReserveResponse>(reservedRequest);
            if(!gateWayResult.success)
            {
                await dialogCoordinator.ShowMessageAsync(this, "警告!", $"预约失败!{gateWayResult.message}");
                return;
            }
            outpReserveResponse = gateWayResult.@object;
            reserveVisib = Visibility.Collapsed;
            await dialogCoordinator.ShowMessageAsync(this, "成功!", $"预约成功!");
            if(Global.RuntimeEnv!= "System")
                this.localWindow?.Close();
        });
    }
}
